package com.ponhu.ea2.goodsCenter.provider.service;

import com.google.common.collect.Lists;
import com.ponhu.ea2.goodsCenter.provider.task.GoodsDataSyncTask;
import com.ponhu.ea2.vo.GoodsDataAttributeSyncVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 胖总管数据初始化接口
 *
 * @author zhaokai
 */
@Slf4j
@Service
public class GoodsInitDataSyncService {

    /**
     * List分割条数
     */
    private final Integer LIST_LIMIT = 20000;

    @Resource
    GoodsDataSyncService goodsDataSyncService;

    /**
     * 商品属性数据同步
     */
    public void goodsAttributeDataSync(List<GoodsDataAttributeSyncVo> goodsDataAttributeSyncVos) {
        try {
            // 自定义线程池,核心线程为5,最大线程为20,队列为500
            ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(6, 20, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(500), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
            // 开启线程超时自动关闭
            threadPoolExecutor.allowCoreThreadTimeOut(true);
            // 按指定条数进行数据分割处理
            List<List<GoodsDataAttributeSyncVo>> parts = Lists.partition(goodsDataAttributeSyncVos, LIST_LIMIT);
            parts.stream().forEach(list -> {
                threadPoolExecutor.execute(new GoodsDataSyncTask(goodsDataSyncService, goodsDataAttributeSyncVos));
            });
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}
